package com.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.entity.Record;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.IRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zgg
 * @since 2021-08-24
 */
@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private IRecordService iRecordService;
    @PostMapping()
    public void addRecord(@RequestBody Record record, HttpSession session){
        User user = (User)session.getAttribute("user");
        record.setCreateBy(user.getUsername());
        record.setCreateDate(LocalDateTime.now());
        iRecordService.save(record);
    }
    @DeleteMapping("/{id}")
    public void removeRecord(@PathVariable("id") Integer id){
        iRecordService.removeById(id);
    }
    @GetMapping("/{id}")
    public Record showOneRecord(@PathVariable("id") Integer id){
        Record record = iRecordService.getById(id);
        return record;
    }
    @GetMapping("/selectRecordsByStuId/{stuId}")
    public List<Record> showRecord(@PathVariable("stuId") Integer stuId){
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.eq("stuId",stuId);
        return iRecordService.list(wrapper);
    }
    @PutMapping("/{id}")
    public void updateRecord(@PathVariable("id")Integer id,@RequestBody Record record,HttpSession session){
        User user = (User)session.getAttribute("user");
        record.setCreateBy(user.getUsername());
        record.setCreateDate(LocalDateTime.now());
        iRecordService.updateById(record);
    }
   @GetMapping("/{pageNum}/{pageSize}")
    public IPage<Record> showPageRecord(@PathVariable("pageNum") Integer pageNum,
                                       @PathVariable("pageSize") Integer pageSize){
        Page<Record> page = new Page<>(pageNum,pageSize);
        IPage<Record> iPage = iRecordService.page(page, null);
        return iPage;
    }
    @GetMapping("/search")
    public PageInfo<Record> showRecordsAndSName(Integer pageNum, Integer pageSize,
                                                String name, String sName){
        PageInfo<Record> rp = iRecordService.showRecordsAndSName(pageNum, pageSize, name, sName);
        System.out.println("rp = " + rp);
        return rp;
    }

}

